from types import FunctionType
from collections import OrderedDict

from django.db.models import Q,Count,Sum
from django.shortcuts import render
from django.http import JsonResponse

from web import models
from web.utils.pager import Pagernation


def attackip_list(request, pk):
    list_display = [
        'sip',
        'ioc_type',
        'sga',
        'last_atk_svr',
        'atknum',
        'cet_atksvr_num',
        'dip',
        'dpt',
        'last_atk_time'
    ]
    search_list = [
        'sip__contains',
        'dip__contains',
        'dpt__contains',
        'sga__contains',
        'ioc_type__contains'
    ]
    keyword = request.GET.get("keyword", "").strip()
    con = Q()
    con.connector = "OR"
    if keyword:
        for item in search_list:
            con.children.append((item, keyword))
    obj = models.K01.objects.filter(id=pk).first()
    date_time = obj.create_datetime
    queryset = models.K01AttackIp.objects.filter(con). \
        filter(create_datetime__year=date_time.year,
               create_datetime__month=date_time.month,
               create_datetime__day=date_time.day).order_by('-atknum')
    model_class = models.K01AttackIp
    pager = Pagernation(request, queryset)
    # 1.处理表头
    header_list = []
    if list_display:
        for key_or_func in list_display:
            if isinstance(key_or_func, FunctionType):
                header_list.append(key_or_func(None, True))
            else:
                verbose_name = model_class._meta.get_field(key_or_func).verbose_name
                header_list.append(verbose_name)
    else:
        header_list.append(model_class._meta.model_name)
    # 2.处理表格内容
    data_list = queryset[pager.start:pager.end]
    body_list = []
    for row in data_list:
        tr_list = []
        if list_display:
            for key_or_func in list_display:
                if isinstance(key_or_func, FunctionType):
                    tr_list.append(key_or_func(row, False))
                else:
                    tr_list.append('' if getattr(row, key_or_func) == None else getattr(row, key_or_func))
        else:
            tr_list.append(row)
        body_list.append(tr_list)

    context = {
        'body_list': body_list,
        'header_list': header_list,
        'pager': pager,
        'keyword': keyword
    }
    return render(request, 'list.html', context)


